import requests
import re
import time
from duanxinbao import task


# 获取丁香园实时页面
def get_dxy_html(url):
    headers = {
        # 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1',
        'User-Agent':'Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 79.0.3945.79Safari / 537.36',
        # 'Host':'3g.dxy.cn'
    }
    try:
        data = requests.get(url, headers=headers)
    except Exception as e:
        print(e)
    else:
        data.encoding = 'utf-8'
        html = data.text
        return html

# 提取信息
def get_info(html):
    # 当前时间
    this_time = time.strftime('%m-%d %H:%M', time.localtime(time.time()))
    time_content = '截至 ' + this_time + '\n'
    # 提取省级信息
    pattern1 = '<script id="getAreaStat">try { window.getAreaStat = (.*?)</script>'
    province_info_list = re.findall(pattern1, html, re.S)
    if province_info_list:  # 如果省级信息正常，提取全国数据
        province_text = ''
        info = eval(province_info_list[0].replace('}catch(e){}', ''))
        # 在html中提取全国数据
        confirmedCount = 0
        curedCount = 0
        deadCount = 0
        for n in info:
            confirmedCount += n['confirmedCount']
            curedCount += n['curedCount']
            deadCount += n['deadCount']
        national_message = '全国确诊%s例，治愈%s例，死亡%s例。其中：\n' % (confirmedCount, curedCount, deadCount)
        # 处理省份数据
        for i in info:
            if i['provinceName'] == '北京市':  # 设置省份
                province1 = '北京：确诊%d例，治愈%d例，死亡%d例。\n' % (i['confirmedCount'],
                                                           i['curedCount'], i['deadCount'])
                province_text += province1
            elif i['provinceName'] == '河南省':  # 设置省份
                province2 = '河南：确诊%d例，治愈%d例，死亡%d例。\n' % (i['confirmedCount'],
                                                           i['curedCount'], i['deadCount'])
                province_text += province2
                for p in i['cities']:
                    if p['cityName'] == '郑州':  # 设置城市
                        city1 = '（郑州：确诊%d例，治愈%d例，死亡%d例。） \n' % (p['confirmedCount'],
                                                           p['curedCount'], p['deadCount'])
                        province_text += city1

        return time_content + national_message + province_text + '（信息来源：丁香医生）'
    else:
        print('无结果，请重新刷新')
        return None

def run():
    enterid = clicktime = str(int(time.time()))
    url = 'http://3g.dxy.cn/newh5/view/pneumonia?scene=2&clicktime=' + clicktime + '&enterid=' + enterid + 'from=timeline&isappinstalled=0'
    html = get_dxy_html(url)
    info = get_info(html)
    task(info)


if __name__ == '__main__':
    run()
